﻿$(document).ready(function () {
    
});

//////////////////////////////////////////////////////////
// Main functionality
//////////////////////////////////////////////////////////
var gchart = {
    // Declarations
    urls: {
        dashboard: Routes.Dashboard,
        dashboardDownloadAsCSV: Routes.DashboardCSV
    },
    sel: {
        start: '.start',
        end: '.end',
        userID: '#userID',
        storeID: '#storeID',
        hideRevoked: "#hideRevoked",
        dashboard: 'divData',
        table: 'table',
        groupSelect: '#groupSelect',
        domainSelect: '#domainSelect',
        storeSelect: '.storeSelect',
        chartButton: 'button#chart',
        tableButton: 'button#table',
        divData: '#divData'
    },
    constants: {
        barLineWidth: 0,
        pieWidth: 0,
        currentRequest: ''
    },
    // Dashboard related operations
    Dashboard: {
        GetParameters: function () {
            var request = new Object();

            request.UserID = $(gchart.sel.userID).val();
            request.Start = $(gchart.sel.start).val() == '' ? null : $(gchart.sel.start).val();
            request.End = $(gchart.sel.end).val() == '' ? null : $(gchart.sel.end).val();
            request.GroupTypeID = $(gchart.sel.groupSelect).val() == '' ? null : $(gchart.sel.groupSelect).val();
            request.StoreID = $(gchart.sel.storeID).val() == 1 ? null : $(gchart.sel.storeID).val();
            request.DomainID = $(gchart.sel.domainSelect).val() == '' || $(gchart.sel.storeID).val() == 1 ? null : $(gchart.sel.domainSelect).val();
            request.HideRevoked = $(gchart.sel.hideRevoked).is(':checked');

            return request;
        },
        ExportCSV: function () {
            gchart.constants.currentRequest = gchart.Dashboard.GetParameters();

            document.location = gchart.urls.dashboardDownloadAsCSV + "?parameter=" + JSON.stringify(gchart.constants.currentRequest)

            layout.Loaded();
        },
        // Gets data 
        Render: function () {
            gchart.constants.barLineWidth = $('#' + gchart.sel.dashboard).width() * 0.75;
            gchart.constants.pieWidth = $('#' + gchart.sel.dashboard).width() * 0.24;

            gchart.constants.currentRequest = gchart.Dashboard.GetParameters();

            gchart.Ajax.Get(gchart.Dashboard.Draw);
        },
        // Renders the dashboard
        Draw: function (response) {
            if ($(gchart.sel.chartButton).hasClass('active')) {
                gchart.Dashboard.DrawChart(response);
            }

            if ($(gchart.sel.tableButton).hasClass('active')) {
                gchart.Dashboard.DrawTable(response);
            }

            layout.Loaded();
        },
        // Renders chart of data
        DrawChart: function (response) {
            if (response.GraphType == 0) {
                gchart.Dashboard.DrawBar(response);
            }

            if (response.GraphType == 1) {
                gchart.Dashboard.DrawLine(response);
            }
        },
        // Create and draw the visualization.
        // Bar
        DrawBar: function (response) {
            var charts = [];
            var titles = [];
            var domains = [];
            var domain = '';

            var data = gchart.Dashboard.GetCommonData();

            for (var i = 0; i < response.BarLineChartSetList.length; i++) {
                if (response.BarLineChartSetList[i].YAxis != domain) {
                    domain = response.BarLineChartSetList[i].YAxis;
                    domains.push(domain);
                    titles.push(domain + response.GraphTitle.replace('All Stores, All domains', ''));

                    if (data.getNumberOfRows() > 0) {
                        charts.push(data);
                        data = gchart.Dashboard.GetCommonData();
                    }
                }

                gchart.Dashboard.AddBarLineRows(data, response, i);
            }

            if (data.getNumberOfRows() > 0) {
                charts.push(data);
            }

            $('#' + gchart.sel.dashboard).empty();

            for (var j = 0; j < titles.length; j++) {
                barDiv = "<div id='bar_" + j + "' style='border-style: ridge; border-width: 1px; border-color: #DDDDDD; float: left; width: " + gchart.constants.barLineWidth + "'></div>";
                barDiv += "<div id='pie_" + j + "' style='border-style: ridge; border-width: 1px; border-color: #DDDDDD; float: left; width: " + gchart.constants.pieWidth + "'></div>";
                barDiv += "<div style='clear: both; margin-bottom: 10px'>"

                $('#' + gchart.sel.dashboard).append(barDiv);

                new google.visualization.BarChart(document.getElementById('bar_' + j)).draw(charts[j],
                {
                    title: titles[j],
                    vAxis: { title: "" },
                    hAxis: { title: "" },
                    width: gchart.constants.barLineWidth,
                    fontName: "Helvetica",
                    fontSize: 13,
                    chartArea: { left: '8%', width: '92%' },
                    legend: { position: 'bottom' }
                });

                gchart.Dashboard.DrawPie(response, j, domains[j]);
            }
        },
        // Create and draw the visualization.
        // Line
        DrawLine: function (response) {
            var charts = [];
            var titles = [];
            var domains = [];
            var domain = '';

            var data = gchart.Dashboard.GetCommonData();

            for (var i = 0; i < response.BarLineChartSetList.length; i++) {
                if (response.BarLineChartSetList[i].YAxis != domain) {
                    domain = response.BarLineChartSetList[i].YAxis;
                    domains.push(domain);
                    titles.push(domain + response.GraphTitle.replace('All Stores, All domains', ''));

                    if (data.getNumberOfRows() > 0) {
                        charts.push(data);
                        data = gchart.Dashboard.GetCommonData();
                    }
                }

                gchart.Dashboard.AddBarLineRows(data, response, i);
            }

            if (data.getNumberOfRows() > 0) {
                charts.push(data);
            }

            $('#' + gchart.sel.dashboard).empty();

            for (var j = 0; j < titles.length; j++) {
                lineDiv = "<div id='line_" + j + "' style='border-style: ridge; border-width: 1px; border-color: #DDDDDD; float: left; width: " + gchart.constants.barLineWidth + "'></div>";
                lineDiv += "<div id='pie_" + j + "' style='border-style: ridge; border-width: 1px; border-color: #DDDDDD; float: left; width: " + gchart.constants.pieWidth + "'></div>";
                lineDiv += "<div style='clear: both; margin-bottom: 10px'>"

                $('#' + gchart.sel.dashboard).append(lineDiv);

                new google.visualization.LineChart(document.getElementById('line_' + j)).draw(charts[j],
                {
                    title: titles[j],
                    vAxis: { title: "Number of ...", baseline: 0 },
                    width: gchart.constants.barLineWidth,
                    fontName: "Helvetica",
                    fontSize: 13,
                    chartArea: { left: '8%', width: '92%' },
                    legend: { position: 'right' }
                });

                gchart.Dashboard.DrawPie(response, j, domains[j]);
            }
        },
        // Create and draw the visualization.
        // Pie
        DrawPie: function (response, id, domain) {
            var data = new google.visualization.DataTable();

            data.addColumn('string', 'coupon'); //response.PieChartSetList[0].Coupon
            data.addColumn('number', 'sessions'); //response.PieChartSetList[0].NumberSessions

            for (var i = 0; i < response.PieChartSetList.length; i++) {
                if (domain == response.PieChartSetList[i].YAxis) {
                    var conversion = Math.round(100 * response.PieChartSetList[i].NumberOrdersWithPopUps / response.PieChartSetList[i].NumberPopUps);

                    if (isNaN(conversion)) {
                        conversion = "";
                    }
                    else {
                        conversion = " [Conversion: " + conversion + "%]";
                    }

                    data.addRows([
                        [response.PieChartSetList[i].Coupon == "" ?
                            "No PopUp" + " " + conversion :
                            response.PieChartSetList[i].Coupon + " " + conversion,
                        response.PieChartSetList[i].NumberSessions]
                    ]);
                }
            }

            new google.visualization.PieChart(document.getElementById('pie_' + id)).draw(data,
                {
                    title: "Coupons",
                    legend: { position: 'none' },
                    fontName: "Helvetica",
                    fontSize: 13,
                    width: gchart.constants.pieWidth,
                    pieSliceText: 'value',
                    is3D: true
                });
        },
        // Renders table of data
        DrawTable: function (response) {
            var data = gchart.Dashboard.GetCommonData();

            data.addColumn('string', 'Period');
            data.addColumn('number', 'Year');

            for (var i = 0; i < response.BarLineChartSetList.length; i++) {
                data.addRows([
                    [response.BarLineChartSetList[i].YAxis,
                    response.BarLineChartSetList[i].NumberOrdsNoPopUp,
                    response.BarLineChartSetList[i].NumberOrdsWithPopUp,
                    response.BarLineChartSetList[i].NumberPopUps,
                    response.BarLineChartSetList[i].NumberSessions,
                    response.BarLineChartSetList[i].XAxisValue,
                    response.BarLineChartSetList[i].Year]
                ]);
            }

            var table = new google.visualization.Table(document.getElementById(gchart.sel.dashboard));
            table.draw(data, null);
        },
        // Get common for all methods data
        GetCommonData: function () {
            var data = new google.visualization.DataTable();

            data.addColumn('string', 'Store');
            data.addColumn('number', 'Number of Orders Without PopUp');
            data.addColumn('number', 'Number of Orders With PopUp');
            data.addColumn('number', 'Number of PopUps');
            data.addColumn('number', 'Number of Sessions');

            return data;
        },
        // Add common for all methods rows
        AddBarLineRows: function (data, response, i) {
            data.addRows([
                    [response.BarLineChartSetList[i].XAxisValue,
                    response.BarLineChartSetList[i].NumberOrdsNoPopUp,
                    response.BarLineChartSetList[i].NumberOrdsWithPopUp,
                    response.BarLineChartSetList[i].NumberPopUps,
                    response.BarLineChartSetList[i].NumberSessions]
                ]);
        }
    },
    // Ajax related operations
    Ajax: {
        // Gets data server
        Get: function (callback) {
            $.ajax({
                traditional: true,
                async: true,
                cache: false,
                type: "GET",
                data: { parameter: JSON.stringify(gchart.constants.currentRequest) },
                url: gchart.urls.dashboard,
                success: function (response) {
                    callback(response);
                },
                error: function (err) {
                    alert(err.responseText);
                },
                contentType: "application/json",
                dataType: "json"
            });
        }
    }
};